import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import request from '@/utils/request'

interface User {
  id: number
  username: string
  email: string
  avatar?: string
}

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))

  const isLoggedIn = computed(() => !!token.value)

  const login = async (username: string, password: string) => {
    try {
      const response = await request.post('/auth/login', {
        username,
        password
      })
      
      token.value = response.data.token
      user.value = response.data.user
      if (token.value) {
        localStorage.setItem('token', token.value)
      }
      
      return response
    } catch (error) {
      throw error
    }
  }

  const register = async (username: string, email: string, password: string) => {
    try {
      const response = await request.post('/auth/register', {
        username,
        email,
        password
      })
      return response
    } catch (error) {
      throw error
    }
  }

  const logout = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
  }

  const getUserInfo = async () => {
    try {
      const response = await request.get('/user/info')
      user.value = response.data
      return response
    } catch (error) {
      logout()
      throw error
    }
  }

  return {
    user,
    token,
    isLoggedIn,
    login,
    register,
    logout,
    getUserInfo
  }
})